﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using BaseLinQ.DataContex;
using Core;

namespace RBAC
{
    public class PhanQuyenNguoiDungLogic
    {
        static string strConnectionString = ConfigurationSettings.AppSettings["ConnectString"];
        RBACDataContext db = null;
        // static Log _logFile = new Log();
        public List<tbl_VaiTroNguoiDungDonVi> lstMenu = null;
        public List<tbl_VaiTroNguoiDungDonVi> lstMenuTmp = null;

        public DataTable GetListPaging(int intStart, string strSort, string strDir, int intLimit, String strFilter)
        {
            DataTable dtbl = null;
            DataSet dts = null;
            List<object> lstNhatKyVaoRa = new List<object>();
            int intTotal = 0;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[8];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@limit";
                commandParameter[0].Value = intLimit;

                commandParameter[1] = new SqlParameter();
                commandParameter[1].ParameterName = "@filter";
                commandParameter[1].Value = strFilter;

                commandParameter[2] = new SqlParameter();
                commandParameter[2].ParameterName = "@start";
                commandParameter[2].Value = intStart;

                commandParameter[3] = new SqlParameter();
                commandParameter[3].ParameterName = "@sort";
                commandParameter[3].Value = strSort;

                commandParameter[4] = new SqlParameter();
                commandParameter[4].ParameterName = "@dir";
                commandParameter[4].Value = strDir;



                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(strConnectionString, "sp_PhanQuyenNguoiDung_Select", commandParameter);
                    if (dts != null)
                    {
                        if (dts.Tables.Count > 0)
                        {
                            if (dts.Tables[0].Rows.Count > 0)
                            {
                                intTotal = int.Parse("0" + dts.Tables[0].Rows[0]["Total"].ToString());
                                dtbl = dts.Tables[0];
                                dts = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //   _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs GetListPaging Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            //intCount = intTotal;
            return dtbl;
        }

        /// <summary>
        /// Lấy danh sách phân quyền theo ID người dùng
        /// </summary>
        /// <param name="lngNguoiDungID"></param>
        /// <returns></returns>
        public DataTable GetListByNguoiDungID(long lngNguoiDungID)
        {
            DataTable dtbl = null;
            DataSet dts = null;
            List<object> lstNhatKyVaoRa = new List<object>();
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@nguoiDungID";
                commandParameter[0].Value = lngNguoiDungID;

                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(strConnectionString, "sp_PhanQuyen_SelectByNguoiDung", commandParameter);
                    if (dts != null)
                    {
                        if (dts.Tables.Count > 0)
                        {
                            if (dts.Tables[0].Rows.Count > 0)
                            {
                                dtbl = dts.Tables[0];
                                dts = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs GetListByNguoiDungID Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            return dtbl;
        }

        /// <summary>
        /// Lấy thao tác theo ID
        /// </summary>
        /// <param name="_lngVaiTroNguoiDungDonViID"></param>
        /// <returns></returns>
        public tbl_VaiTroNguoiDungDonVi GetByID(long _lngVaiTroNguoiDungDonViID)
        {
            tbl_VaiTroNguoiDungDonVi objRes = null;
            db = new RBACDataContext(strConnectionString);
            try
            {
                objRes = (from m in db.tbl_VaiTroNguoiDungDonVis
                          where m.pk_iVaiTroNguoiDungID == _lngVaiTroNguoiDungDonViID
                          select m).FirstOrDefault<tbl_VaiTroNguoiDungDonVi>();
            }
            catch (Exception ex)
            {
                //   _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs GetByID Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            return objRes;
        }

        /// <summary>
        /// Them moi thao tác
        /// </summary>
        /// <param name="_objAdd"></param>
        /// <returns></returns>
        public bool Insert(tbl_VaiTroNguoiDungDonVi _objAdd, long _lstVaiTroID)
        {
            bool blnFalse = false;
            db = new RBACDataContext(strConnectionString);
            using (var trans = new TransactionScope())
            {
                try
                {
                    //Với mỗi VaiTroID thêm một bản ghi
                    List<tbl_VaiTroNguoiDungDonVi> lstVaiTroNguoiDungDonVi = (from vnd1 in db.tbl_VaiTroNguoiDungDonVis
                                                                              where vnd1.fk_iDonViID == _objAdd.fk_iDonViID
                                                                              && vnd1.fk_iNguoiDungID == _objAdd.fk_iNguoiDungID
                                                                              && vnd1.bKichHoat == true
                                                                              select vnd1).ToList<tbl_VaiTroNguoiDungDonVi>();
                    if (lstVaiTroNguoiDungDonVi != null && lstVaiTroNguoiDungDonVi.Count > 0)
                    {

                        //Nếu ID vai trò đã tồn tại trong CSDL
                        if (_lstVaiTroID.Equals(lstVaiTroNguoiDungDonVi.FirstOrDefault()))
                        {
                            lstVaiTroNguoiDungDonVi.Remove(lstVaiTroNguoiDungDonVi.FirstOrDefault()); //Xóa khỏi danh sách cần xóa
                        }


                    }

                    lstVaiTroNguoiDungDonVi = new List<tbl_VaiTroNguoiDungDonVi>();
                    
                        tbl_VaiTroNguoiDungDonVi vnd = new tbl_VaiTroNguoiDungDonVi();
                        vnd.fk_iNguoiDungID = _objAdd.fk_iNguoiDungID;
                        vnd.fk_iDonViID = _objAdd.fk_iDonViID;
                        vnd.fk_iVaiTroID = _lstVaiTroID;
                        vnd.bKichHoat = true;
                        vnd.sGhiChu = _objAdd.sGhiChu;
                        lstVaiTroNguoiDungDonVi.Add(vnd);
                        InsertMienDuLieu(db, _objAdd.fk_iNguoiDungID, _objAdd.fk_iDonViID, _lstVaiTroID);
                   
                    db.tbl_VaiTroNguoiDungDonVis.InsertAllOnSubmit(lstVaiTroNguoiDungDonVi);
                    db.SubmitChanges();
                    lstVaiTroNguoiDungDonVi = null;
                    blnFalse = true;
                    trans.Complete();
                }
                catch (Exception ex)
                {
                    // _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs Insert Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                }
            }
            db = null;
            return blnFalse;
        }


        public bool DeleteMienDuLieu(RBACDataContext _db, long _lngNguoiDungID, long _lngDonViID, long _lngVaiTroID)
        {
            bool blnRes = false;
            try
            {
                List<tbl_NguoiDungQuyenDonVi> lstMienDuLieu = (from ndq in _db.tbl_NguoiDungQuyenDonVis
                                                               from qv in _db.tbl_QuyenVaiTros
                                                               where ndq.fk_iQuyenVaiTroID == qv.pk_iQuyenVaiTroID
                                                               && ndq.fk_iNguoiDungID == _lngNguoiDungID
                                                               && ndq.fk_iDonViID == _lngDonViID
                                                               && qv.fk_iVaiTroID == _lngVaiTroID
                                                               select ndq).ToList<tbl_NguoiDungQuyenDonVi>();
                if (lstMienDuLieu != null && lstMienDuLieu.Count > 0)
                {
                    _db.tbl_NguoiDungQuyenDonVis.DeleteAllOnSubmit(lstMienDuLieu);
                    _db.SubmitChanges();
                    blnRes = true;
                }
            }
            catch (Exception ex)
            {
                //  _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs DeleteMienDuLieu Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            return blnRes;
        }

        public bool InsertMienDuLieu(RBACDataContext _db, long _lngNguoiDungID, long _lngDonViID, long _lngVaiTroID)
        {
            bool blnRes = false;
            try
            {
                List<tbl_QuyenVaiTro> lstQuyenVaiTro = (from qv in _db.tbl_QuyenVaiTros
                                                        where qv.fk_iVaiTroID == _lngVaiTroID
                                                        select qv).ToList<tbl_QuyenVaiTro>();
                if (lstQuyenVaiTro != null && lstQuyenVaiTro.Count > 0)
                {
                    List<tbl_NguoiDungQuyenDonVi> lstMienDuLieu = new List<tbl_NguoiDungQuyenDonVi>();
                    foreach (tbl_QuyenVaiTro qv in lstQuyenVaiTro)
                    {
                        tbl_NguoiDungQuyenDonVi ndq = new tbl_NguoiDungQuyenDonVi();
                        ndq.fk_iDonViID = _lngDonViID;
                        ndq.fk_iNguoiDungID = _lngNguoiDungID;
                        ndq.fk_iQuyenVaiTroID = qv.pk_iQuyenVaiTroID;
                        lstMienDuLieu.Add(ndq);
                    }
                    _db.tbl_NguoiDungQuyenDonVis.InsertAllOnSubmit(lstMienDuLieu);
                    blnRes = true;
                }
            }
            catch (Exception ex)
            {
                //_logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs InsertMienDuLieu Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            return blnRes;
        }

        /// <summary>
        /// Cap nhat
        /// </summary>
        /// <param name="objEdit"></param>
        /// <returns></returns>
        public bool Update(tbl_VaiTroNguoiDungDonVi objEdit)
        {
            bool blnRes = false;
            db = new RBACDataContext(strConnectionString);
            tbl_VaiTroNguoiDungDonVi objCheck = (from n in db.tbl_VaiTroNguoiDungDonVis
                                                 where n.pk_iVaiTroNguoiDungID != objEdit.pk_iVaiTroNguoiDungID
                                                 && n.fk_iNguoiDungID == objEdit.fk_iNguoiDungID
                                                 && n.fk_iDonViID == objEdit.fk_iDonViID
                                                 && n.fk_iVaiTroID == objEdit.fk_iVaiTroID
                                                 && n.bKichHoat == true
                                                 select n).FirstOrDefault<tbl_VaiTroNguoiDungDonVi>();
            if (objCheck != null)
            {
                blnRes = false;
            }
            else
            {

                try
                {
                    tbl_VaiTroNguoiDungDonVi objOld = (from m in db.tbl_VaiTroNguoiDungDonVis
                                                       where m.pk_iVaiTroNguoiDungID == objEdit.pk_iVaiTroNguoiDungID
                                                       select m).FirstOrDefault<tbl_VaiTroNguoiDungDonVi>();
                    if (objOld != null && objOld.pk_iVaiTroNguoiDungID > 0)
                    {
                        //Nếu chuyển đổi vai trò
                        //1)Xóa hết các bản ghi trong bảng tbl_NguoiDungQuyenDonVi
                        //2)Thêm vào bảng tbl_NguoiDungQuyenDonVi với các quyền - vai trò mới
                        if (objEdit.fk_iVaiTroID != objOld.fk_iVaiTroID)
                        {
                            //1)
                            List<tbl_NguoiDungQuyenDonVi> lstMienDuLieu = (from mdl in db.tbl_NguoiDungQuyenDonVis
                                                                           from qv in db.tbl_QuyenVaiTros
                                                                           where mdl.fk_iQuyenVaiTroID == qv.pk_iQuyenVaiTroID
                                                                           && qv.fk_iVaiTroID == objOld.fk_iVaiTroID
                                                                           && mdl.fk_iDonViID == objOld.fk_iDonViID
                                                                           && mdl.fk_iNguoiDungID == objOld.fk_iNguoiDungID
                                                                           select mdl).ToList<tbl_NguoiDungQuyenDonVi>();
                            List<tbl_VaiTroNguoiDungDonVi> lstVTNDDV = (from m in db.tbl_VaiTroNguoiDungDonVis
                                                                        where m.fk_iDonViID == objOld.fk_iDonViID
                                                                        && m.fk_iNguoiDungID == objOld.fk_iNguoiDungID
                                                                        && m.fk_iVaiTroID == objOld.fk_iVaiTroID
                                                                        select m).ToList<tbl_VaiTroNguoiDungDonVi>();
                            if (lstVTNDDV != null && lstVTNDDV.Count > 0)
                            {
                                db.tbl_VaiTroNguoiDungDonVis.DeleteAllOnSubmit(lstVTNDDV);
                                db.SubmitChanges();
                            }
                            if (lstMienDuLieu != null && lstMienDuLieu.Count > 0)
                            {
                                db.tbl_NguoiDungQuyenDonVis.DeleteAllOnSubmit(lstMienDuLieu);
                                db.SubmitChanges();

                            }
                            //2)
                            List<tbl_QuyenVaiTro> lstQuyenVaiTro = (from qv in db.tbl_QuyenVaiTros
                                                                    where qv.fk_iVaiTroID == objEdit.fk_iVaiTroID
                                                                    select qv).ToList<tbl_QuyenVaiTro>();
                            if (lstQuyenVaiTro != null && lstQuyenVaiTro.Count > 0)
                            {
                                List<tbl_NguoiDungQuyenDonVi> lstMienDuLieuNew = new List<tbl_NguoiDungQuyenDonVi>();
                                List<tbl_VaiTroNguoiDungDonVi> lstVtroNdungDvi = new List<tbl_VaiTroNguoiDungDonVi>();
                                long idCheckVT = 0;
                                foreach (tbl_QuyenVaiTro objQv in lstQuyenVaiTro)
                                {
                                    tbl_NguoiDungQuyenDonVi obj = new tbl_NguoiDungQuyenDonVi();
                                    obj.fk_iNguoiDungID = objEdit.fk_iNguoiDungID;
                                    obj.fk_iDonViID = objEdit.fk_iDonViID;
                                    obj.fk_iQuyenVaiTroID = objQv.pk_iQuyenVaiTroID;
                                    lstMienDuLieuNew.Add(obj);

                                    if (objQv.fk_iVaiTroID != idCheckVT)
                                    {
                                        //Thêm vào bảng VaiTroNguoiDungDonVi
                                        tbl_VaiTro objVT = (from b in db.tbl_VaiTros
                                                            where b.bKichHoat == true
                                                            && b.pk_iVaiTroID == objQv.fk_iVaiTroID
                                                            select b).FirstOrDefault<tbl_VaiTro>();
                                        idCheckVT = objVT.pk_iVaiTroID;
                                        tbl_VaiTroNguoiDungDonVi objVTNDDV = new tbl_VaiTroNguoiDungDonVi();
                                        objVTNDDV.fk_iDonViID = objEdit.fk_iDonViID;
                                        objVTNDDV.fk_iNguoiDungID = objEdit.fk_iNguoiDungID;
                                        objVTNDDV.fk_iVaiTroID = objVT.pk_iVaiTroID;
                                        objVTNDDV.sGhiChu = objEdit.sGhiChu;
                                        objVTNDDV.bKichHoat = true;

                                        lstVtroNdungDvi.Add(objVTNDDV);
                                    }
                                }
                                if (lstMienDuLieuNew.Count > 0)
                                {
                                    db.tbl_NguoiDungQuyenDonVis.InsertAllOnSubmit(lstMienDuLieuNew);
                                    db.SubmitChanges();
                                }
                                if (lstVtroNdungDvi.Count > 0)
                                {
                                    db.tbl_VaiTroNguoiDungDonVis.InsertAllOnSubmit(lstVtroNdungDvi);
                                    db.SubmitChanges();
                                }
                            }
                        }
                        else
                            //Cập nhật lại miền dữ liệu khi có sự thay đổi về miền dữ liệu đơn vị
                            if (objEdit.fk_iDonViID != objOld.fk_iDonViID)
                            {
                                //Cập nhật miền dữ liệu
                                try
                                {
                                    List<tbl_NguoiDungQuyenDonVi> lstMienDuLieu = (from mdl in db.tbl_NguoiDungQuyenDonVis
                                                                                   from qv in db.tbl_QuyenVaiTros
                                                                                   where mdl.fk_iQuyenVaiTroID == qv.pk_iQuyenVaiTroID
                                                                                   && qv.fk_iVaiTroID == objOld.fk_iVaiTroID
                                                                                   && mdl.fk_iDonViID == objOld.fk_iDonViID
                                                                                   && mdl.fk_iNguoiDungID == objOld.fk_iNguoiDungID
                                                                                   select mdl).ToList<tbl_NguoiDungQuyenDonVi>();
                                    if (lstMienDuLieu != null && lstMienDuLieu.Count > 0)
                                    {
                                        foreach (tbl_NguoiDungQuyenDonVi obj in lstMienDuLieu)
                                        {
                                            obj.fk_iDonViID = objEdit.fk_iDonViID;
                                        }
                                        db.SubmitChanges();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //  _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs Update Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                                }
                            }
                        //Cập nhật vai trò
                        objOld.fk_iDonViID = objEdit.fk_iDonViID;
                        objOld.fk_iVaiTroID = objEdit.fk_iVaiTroID;
                        objOld.fk_iNguoiDungID = objEdit.fk_iNguoiDungID;
                        objOld.sGhiChu = objEdit.sGhiChu;
                        db.SubmitChanges();
                        blnRes = true;
                    }
                }
                catch (Exception ex)
                {
                    //  _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs Update Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                }
            }
            db = null;
            return blnRes;
        }

        /// <summary>
        /// Xoa thao tác
        /// </summary>
        /// <param name="_pk_iPhanQuyenNguoiDungID"></param>
        /// <returns></returns>
        public bool Delete(long _pk_iPhanQuyenNguoiDungID)
        {
            bool blnRes = false;
            db = new RBACDataContext(strConnectionString);
            try
            {
                //Xóa vai trò
                tbl_VaiTroNguoiDungDonVi objPhanQuyenOld = (from m in db.tbl_VaiTroNguoiDungDonVis
                                                            where m.pk_iVaiTroNguoiDungID == _pk_iPhanQuyenNguoiDungID
                                                            && m.bKichHoat == true
                                                            select m).FirstOrDefault<tbl_VaiTroNguoiDungDonVi>();
                if (objPhanQuyenOld != null && objPhanQuyenOld.pk_iVaiTroNguoiDungID > 0)
                {
                    objPhanQuyenOld.bKichHoat = false;
                    db.SubmitChanges();
                    //Xóa miền dữ liệu
                    try
                    {
                        List<tbl_NguoiDungQuyenDonVi> lstMienDuLieu = (from mdl in db.tbl_NguoiDungQuyenDonVis
                                                                       from qv in db.tbl_QuyenVaiTros
                                                                       where mdl.fk_iQuyenVaiTroID == qv.pk_iQuyenVaiTroID
                                                                       && qv.fk_iVaiTroID == objPhanQuyenOld.fk_iVaiTroID
                                                                       && mdl.fk_iDonViID == objPhanQuyenOld.fk_iDonViID
                                                                       && mdl.fk_iNguoiDungID == objPhanQuyenOld.fk_iNguoiDungID
                                                                       select mdl).ToList<tbl_NguoiDungQuyenDonVi>();
                        if (lstMienDuLieu != null && lstMienDuLieu.Count > 0)
                        {
                            db.tbl_NguoiDungQuyenDonVis.DeleteAllOnSubmit(lstMienDuLieu);
                            db.SubmitChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        //   _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs Delete Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
                    }
                    blnRes = true;
                }
            }
            catch (Exception ex)
            {
                //   _logFile.Write("Exception when using PhanQuyenNguoiDungLogic.cs Delete Message:" + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
            }
            db = null;
            return blnRes;
        }

        public bool Insert(tbl_VaiTroNguoiDungDonVi objPhanQuyen)
        {
            throw new NotImplementedException();
        }
    }
}
